package com.bobo.controller.front.user;

import com.bobo.annotations.RequestBody;
import com.bobo.annotations.RequestMapping;
import com.bobo.annotations.RequestMethod;
import com.bobo.controller.base.BaseServlet;
import com.bobo.controller.front.pub.SetPage;
import com.bobo.dto.Counts;
import com.bobo.dto.Page;
import com.bobo.dto.VCTopic;
import com.bobo.model.Favourite;
import com.bobo.model.Photo;
import com.bobo.model.Topic;
import com.bobo.model.User;
import com.bobo.service.favourite.FavouriteServiceImpl;
import com.bobo.service.favourite.IFavouriteService;
import com.bobo.service.photo.IPhotoService;
import com.bobo.service.photo.PhotoServiceImpl;
import com.bobo.service.topic.ITopicService;
import com.bobo.service.topic.TopicServiceImpl;
import com.bobo.service.user.IUserService;
import com.bobo.service.user.UserServiceImpl;
import com.bobo.util.UploadFiles;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * Created by bobo on 16-10-28.
 */
@WebServlet(name = "user",urlPatterns = {"/user/*"})
public class UserController extends BaseServlet{

    private IUserService userService = new UserServiceImpl();
    private ITopicService topicService = new TopicServiceImpl();
    private IFavouriteService favouriteService = new FavouriteServiceImpl();
    private IPhotoService photoService = new PhotoServiceImpl();



    @RequestMapping(value = "/updPassword", method = RequestMethod.POST)
    public String updp(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        String old = request.getParameter("old");
        String newpwd1 = request.getParameter("newpwd1");
        String newpwd2 = request.getParameter("newpwd2");


        if (newpwd1.equals(newpwd2)) {
            User user = userService.updQuery(id, old);
            if(user.getId()!=null){
                user.setPassword(newpwd1);
                userService.updPwd(user);
                return "redirect:/user/userinfo";
            }
        }
        return "fail";
    }
    @RequestMapping("/updPassword")
    public String updp(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        request.setAttribute("user", user);
        return "jsp/front/user/updPassword";
    }

    @RequestMapping(value = "/upd", method = RequestMethod.POST)
    public String upd1(HttpServletRequest request, HttpServletResponse response) {
        //跟新资料

        User user = (User)request.getSession().getAttribute("user");

        String name = request.getParameter("name");
        int sex = Integer.parseInt(request.getParameter("sex"));
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");


        user.setName(name);
        user.setSex(sex);
        user.setPhone(phone);
        user.setEmail(email);
        user.setAddress(address);

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(birthday);
            java.sql.Date sqldate = new java.sql.Date(date.getTime());
            user.setBirthday(sqldate);
            userService.upd(user);
            return "redirect:/user/userinfo";
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "error";
    }

    @RequestMapping("/upd")
    public String upd1(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        request.setAttribute("user", user);
        return "jsp/front/user/upd";
    }

    @RequestMapping(value = "/updImg", method = RequestMethod.POST)
    public String updImg(HttpServletRequest request, HttpServletResponse response) {
        UploadFiles uploadFiles = new UploadFiles();


        try {
            User user = (User) request.getSession().getAttribute("user");
            Photo oldPhoto = user.getPhoto();

            Map<String, Object[]> map = uploadFiles.upload(request);
            Object[] fileNames = map.get("fileName");
            Object[] pid = map.get("pid");


            Photo photo = new Photo();
            if (fileNames!=null && fileNames.length > 0) {
                /**
                 *  上传头像
                 */
                photo.setImg(fileNames[0].toString());
                photo.setStatus(0);
                Integer newPid = photoService.create(photo);
                photo = photoService.getPhoto(newPid);
            }else {
                /**
                 * 使用公共头像
                 */
                Photo rePhoto = photoService.getPhoto(Integer.parseInt(pid[0].toString()));
                if(rePhoto.getId() != null) {
                    photo = rePhoto;
                }
            }
            user.setPhoto(photo);
            userService.upd(user);

            /**
             * 当前图像与旧头像不符并且不为公共头像时 删除就头像并删除数据
             */
            if((!Objects.equals(photo.getId(), oldPhoto.getId())) && (oldPhoto.getStatus() != 1)) {
                uploadFiles.delFile(request,oldPhoto.getImg());
                photoService.delete(oldPhoto.getId());
            }
            return "redirect:/user/userinfo";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("/updImg")
    public String updImg(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");

        request.setAttribute("recomImgs", photoService.getList(1));
        request.setAttribute("user", user);
        return "jsp/front/user/updImg";
    }




    @RequestBody
    @RequestMapping("/addFavourite")
    public String favourite(HttpServletRequest request){
        Favourite favourite = new Favourite();
        int id = Integer.parseInt(request.getParameter("id"));
        favourite.setTopicId(id);
        User user = (User) request.getSession().getAttribute("user");
        favourite.setUserId(user.getId());
        favouriteService.create(favourite);
        return "true";
    }
    @RequestBody
    @RequestMapping("/delFavourite")
    public String delFavourite(HttpServletRequest request){
        Favourite favourite = new Favourite();
        int id = Integer.parseInt(request.getParameter("id"));
        favourite.setTopicId(id);
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/user/login";
        }
        favourite.setUserId(user.getId());
        favouriteService.delete(favourite);
        return "true";
    }

    @RequestMapping("/getFavourite")
    public String getFavourite(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");

        int current = 1;
        int pageSize = 5;

        if(request.getParameter("current") != null) {
            current = Integer.parseInt(request.getParameter("current"));
        }

        if(request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        Page<Topic> page = favouriteService.getTopics(user.getId(), current, pageSize);
        request.setAttribute("page",page);
        return "jsp/front/user/favourite";
    }

    @RequestMapping("/publish")
    public String publish(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute("user");

        int current = 1;
        int pageSize = 5;
        int status = 1;

        if(request.getParameter("current") != null) {
            current = Integer.parseInt(request.getParameter("current"));
        }

        if(request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        if(request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("status"));
        }

        Page<VCTopic> page = topicService.getTopicsByUserId(user.getId(), current, pageSize);
        request.setAttribute("page",page);
        return "jsp/front/user/myTopics";
    }

    @RequestMapping("/SignOut")
    public String SignOut(HttpServletRequest request, HttpServletResponse response){
        request.getSession().setAttribute("user",null);
        return "redirect:/index/blog";
    }

    @RequestMapping("/userinfo")
    public String userInfo(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        Counts counts = favouriteService.getCounts(user.getId());
        request.setAttribute("counts",counts);
        return "jsp/front/user/info";
    }



}
